import { defineComponent, onMounted, onBeforeUnmount } from 'vue'
import { ElLoading } from 'element-plus'
import useVuexGetters from '~/hooks/useVuexGetters'
import type { mapViewRoadData } from './typings'
import useAMap from '~/hooks/useAMap'

export default defineComponent({
  name: 'MapView',
  props: ['id', 'setFitView', 'roadData'],
  setup(props: mapViewRoadData, { expose }) {
    const userState = useVuexGetters('user', ['userAddressInfo'])
    onMounted(() => {})
    onBeforeUnmount(() => {
      mapRef.value.clearMap()
      mapRef.value.destroy()
    })
    const loading = ElLoading.service({
      target: `#${props.id}`,
      lock: true,
      text: '加载中'
    })
    const userinfo = JSON.parse(window.localStorage.getItem('userinfo') || '')
    const [mapRef, aMapRef, amapIconRef] = useAMap(
      props.id,
      {
        center: [userinfo.lon, userinfo.lat],
        zoom: 11,
        resizeEnable: true
      },
      initAMap
    )
    const searchRoad = () => {
      setTimeout(() => {
        handleSearchAddressSelectList()
      }, 1000)
    }
    // 搜索道路点位
    const handleSearchAddressSelectList = () => {
      const placeSearch = new aMapRef.value.PlaceSearch({
        city: userState.userAddressInfo.value.city,
        citylimit: false,
        type: '地名地址信息;交通地名;道路名'
      }) // 构造地点查询类
      const array: any[] = []
      props.roadData.forEach((el: any) => {
        let data: any = {}
        placeSearch.search(el.assetName, (status: string, result: Record<string, any>) => {
          data = status === 'complete' && result.info === 'OK' ? result.poiList.pois[0] : []
          array.push(data)
          handleAddAMapMarker(data.location.lng, data.location.lat)
        })
      })
    }
    //  添加标点
    const handleAddAMapMarker = (lng: number, lat: number) => {
      const markerPattern = new aMapRef.value.Marker({
        icon: amapIconRef.value,
        position: [lng, lat],
        offset: [-12, -22]
      })
      mapRef.value.add(markerPattern)
    }
    function initAMap() {
      loading.close()
    }
    // 暴露方法给父组建
    expose({
      searchRoad
    })

    return () => <section style="height: 100%;" id={props.id}></section>
  }
})
